from rest_framework.throttling import SimpleRateThrottle
from django.core.cache import cache as default_cache
from drf_template_admin.services.ThrottledException import VerifyCodeThrottledException

class VerifyCodeThrottle(SimpleRateThrottle):
    cache = default_cache
    scope = 'verifyCode'
    THROTTLE_RATES = {'verifyCode': '5/m'}

    def get_cache_key(self, request, view):
        if request.user:
            ident = request.user['pk']   

        return self.cache_format % { 'scope': self.scope, 'ident': ident }
    
    def throttle_failure(self):
        wait = self.wait()
        detail = {
            "code": 10001,
            "data": "访问频率限制",
            'detail': "需等待{}s才能访问".format(int(wait))
        }
        raise VerifyCodeThrottledException(detail)
 